<?php

/* he 学生成绩导入操作 */

class DefaultController extends FController {

    public $user_school_list;
    public $user_subject_list;
    public $user_role_list;
    public $exam_id;
	public function init() {
		parent::init();
		if (empty($this->cLoginUser)) {
			$this->redirect($this->createUrl('/site/login'));
        } else {
            $userLoginUser = $this->cLoginUser;
            $this->user_role_list = isset($userLoginUser['cuser']['role_id']) ? $userLoginUser['cuser']['role_id'] : '';
            $this->user_school_list = isset($userLoginUser['cuser']['school']['school_id']) ? $userLoginUser['cuser']['school']['school_id'] : '';
            $this->user_subject_list = isset($userLoginUser['cuser']['school']['subject_id']) ? $userLoginUser['cuser']['school']['subject_id'] : '';
            $zRow = new ZRole();
            //得到学校对应的考试
            $exam_list = $zRow->_getSchoolExam($this->user_school_list);
            if (!empty($exam_list)) {
                $this->exam_id = implode(',', $exam_list);
		}
        }
		$this->commonScript();
		Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/base.css');
		Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/master.css');
		Yii::app()->clientScript->registerCssFile(THEME_CSS_URL . '/module_Sip.css');
	}
	//导入
	public function actionIndex() {
        Yii::app()->clientScript->registerScriptFile(STATICS_URL . "/js/ajaxfileupload.js");
		$this->title ='考试学生信息导入';
		$conn = Yii::app()->db;
		$limit = 8;
                $where = '';
                if (empty($date['exam_id'])){
                    //权限判断
                    if ($this->user_role_list != 1 && !empty($this->exam_id)) {
                        $where .= ' AND "exam_id" IN (' . $this->exam_id . ')';
                    }
                }
		$date['ztask'] = ZTask::_getExamAll($where);
        // $schoolwhere = ' WHERE "is_del"=0 ';
        // $date['school'] = Nojoin::_getschoolAll($schoolwhere);
        $zEdu = new ZEdu();
        if ($this->user_role_list != 1 && !empty($this->user_school_list)) {
            $date['school'] = $zEdu->_getSchoolInfo($this->user_school_list);
            $where .= " AND \"school_id\" IN (" . $this->user_school_list . ") ";
		}else{
            $date['school'] = $zEdu->_getSchoolInfo();
		}
		$date['exam_id'] = $this->request->getParam('exam_id', 0);
		$data_student = $data = $pages = array();
		if ($date['exam_id'] > 0) {
			$sql = 'SELECT *  FROM "{{import_error}}" WHERE "type"=1 AND "exam_id" =' . $date['exam_id'];
			$count = 'SELECT count("id") FROM "{{import_error}}" WHERE "type"=1 AND "exam_id" =' . $date['exam_id'];
			$data = ZCommon::getDaoPageList($sql, $count, $limit);
			if(!empty($data)){
				$pages = isset($data['pages']) ? $data['pages'] : '';
			}else{
                $data_student = self::_getStudentList($where);
				$pages = isset($data_student['pages']) ? $data_student['pages'] : '';
			}

		}else{
            $data_student = self::_getStudentList($where);
			$pages = isset($data_student['pages']) ? $data_student['pages'] : '';
		}

		$pageUrl = $this->createUrl('/info/default/index', array('exam_id' => $date['exam_id']));
		$this->render('import', array(
		'data' => isset($data['listDatas'])?$data['listDatas']:'',
		'pages' => $pages,
		'data_student' => isset($data_student['listDatas']) ? $data_student['listDatas'] : '',
		'pageUrl' => $pageUrl,
		'date' => $date
		));
	}

    protected function _getStudentList($where = '', $pageSize = 8) {

		$conn = Yii::app()->db;

        if (!empty($where)) {
            $sql = 'SELECT "student_id","student_name","exam_id","class_name","school_id","school_name" FROM "{{student}}" WHERE 1=1 ' . $where;
            $sqlCount = ' SELECT count(*) FROM "{{student}}" WHERE 1=1 ' . $where;
        } else {
            $sql = 'SELECT "student_id","student_name","exam_id","class_name","school_id","school_name" FROM "{{student}}" ';
            $sqlCount = ' SELECT count(*) FROM "{{student}}" ';
		}

		$data = ZCommon::getDaoPageList($sql, $sqlCount, $pageSize);

		return $data;
	}

	

	//高中下载模版
	public function actionUpload() {
		spl_autoload_unregister(array('YiiBase', 'autoload'));
		include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel.php');
		include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel/IOFactory.php');
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->setActiveSheetIndex(0)
		->setCellValue('A1', '准考号')
		->setCellValue('B1', '班级')
		->setCellValue('C1', '科别简称')
		->setCellValue('D1', '姓名')
		->setCellValue('E1', '性别')
		->setCellValue('F1', '中考成绩')
		->setCellValue('G1', '统计')
		->setCellValue('H1', '学校性质')
		->setCellValue('I1', '学校星级')
		->setCellValue('J1', '学籍号')
		->setCellValue('K1', '备注');
		$file_nams = "高中考试学生数据导入模板";
		$file_nams .= ".xls";
		if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) {
			$file_nams = urlencode($file_nams);
			$file_nams = str_replace("+", "%20", $file_nams); // 替换空格
		}
		ob_end_clean();
		header("Content-Type: application/vnd.ms-excel;charset=utf-8");
		header("Content-Disposition: attachment; filename=" . $file_nams);
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
		header('Expires:0');
		header('Pragma:public');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		Yii::app()->end();
		spl_autoload_register(array('YiiBase', 'autoload'));
	}

	//初中下载模版
	public function actionHighupload() {
		spl_autoload_unregister(array('YiiBase', 'autoload'));
		include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel.php');
		include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/extensions/PHPExcel/IOFactory.php');
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->setActiveSheetIndex(0)
		->setCellValue('A1', '准考号')
		->setCellValue('B1', '班级')
		->setCellValue('C1', '姓名')
		->setCellValue('D1', '学籍号')
		->setCellValue('E1', '备注');
		$file_nams = "初中考试学生数据导入模板";
		$file_nams .= ".xls";
		if (preg_match("/MSIE/", $_SERVER["HTTP_USER_AGENT"])) {
			$file_nams = urlencode($file_nams);
			$file_nams = str_replace("+", "%20", $file_nams); // 替换空格
		}
		ob_end_clean();
		header("Content-Type: application/vnd.ms-excel;charset=utf-8");
		header("Content-Disposition: attachment; filename=" . $file_nams);
		header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
		header("Content-Type: application/force-download");
		header('Expires:0');
		header('Pragma:public');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
		$objWriter->save('php://output');
		Yii::app()->end();
		spl_autoload_register(array('YiiBase', 'autoload'));
	}

	//ajax获取联动获取学校
	function actionajaxvalue() {
		//$this->common();

		$tj = '';
		if ($this->user_role_list != 1 && !empty($this->user_school_list)) {
        	$tj .= " AND school_id IN (".$this->user_school_list.")";
		}

		$exm_id = $this->request->getParam('id');
		$school_info = array();
		if (empty($exm_id)) {
			$schoolwhere = ' WHERE "is_del" =0 '.$tj;
			$school_info = Nojoin::_getschoolAll($schoolwhere);
		} else {
			$exam_where = ' WHERE "exam_id" =' . $exm_id.$tj;
			$exam_school = Nojoin::_getexam_schoolALL($exam_where);
			$exam_school_id = array();
			foreach ($exam_school as $k => $v) {
				$exam_school_id[] = $v['school_id'];
			}
			//得到学校信息
			$where = ' WHERE "school_id" IN (' . implode(",", $exam_school_id) . ')';
			$school_info = Nojoin::_getschoolAll($where);
		}
		echo json_encode($school_info);
	}
    //更新功能
    public function actionUpdate(){
        $this->title = '学生信息设置';
        $this->layout = "//layouts/main_window";
        $data = array();
        $sid = $this->request->getParam('sid');
        $eid = $this->request->getParam('eid');
        $zedu = new ZEdu();
        if(!empty($sid) && !empty($eid)){
            $data = $zedu->_getStudentInfo($sid,$eid);
        }
        //保存更新信息
        if (isset($_POST['submit']) && !empty($_POST['submit'])) {
            $status = $zedu->_updStudentInfo($_POST['student_id'],$_POST);

            if ($status) {
                $this->frameAjaxMessage('/info/default/index');
                exit;
            } else {
                $this->frameAjaxMessage(null, '更新失败');
                exit;
            }
        }
        $this->render('update',array(
            'data'  => $data
        ));
    }
    //删除功能
    public function actionDelete(){
        $status = 0;
        $sid = $this->request->getParam('sid');
        $eid = $this->request->getParam('eid');
        if($sid>0 && $eid>0){
            $zedu = new ZEdu();
            $status = $zedu->_delStudent($sid,$eid);
        }
        echo $status;
    }
    
    public function ActionUploadexcel(){
        // 请求参数
        $isAjax = isset($_POST['isajax'])?$_POST['isajax']:0;
        $examID = isset($_POST['exam_id'])?$_POST['exam_id']:0;
        $schoolID = isset($_POST['school_id'])?$_POST['school_id']:0;

        // 非法请求 无响应信息
        if($isAjax!=1 || !$this->request->isPostRequest)
            exit;
        if (!$examID || empty($_FILES['file']['name']) || !$schoolID) {
            Z::ajaxReturn(201, '考试项目,学校,上传文件为必选项');
        }
        
        // 得到学生信息
        $userinfo = $this->cLoginUser;
        if (isset($userinfo['cuser']['role_id']) && $userinfo['cuser']['role_id']!=1) {
            $userid = $userinfo['cuser']['id'];
            $studentinfo = Import::_getstudentinfo($userid);
            if (empty($studentinfo)){
                Z::ajaxReturn(202, '当前用户没有可导入的学校');
            }
            //判断当前用户是否有导入所选学校的权限
            $school_ids = $studentinfo['school_id'];
            if (!strpos($school_ids, $schoolID)) {
                Z::ajaxReturn(203, '当前用户没有导入所选学校的权限');
            }
        }
        
        // 考试验证
        $examwhere = "SELECT \"exam_status\" FROM \"{{exam}}\" WHERE \"exam_id\"='{$examID}'";
        $exam = Yii::app()->db->createCommand($examwhere)->queryRow();
        if(!$exam){
            Z::ajaxReturn(204, '考试不存在');
        }
        if(!isset($exam['exam_status']) && $exam['exam_status']!=1){
            Z::ajaxReturn(205, '本次考试状态不是上传数据');
        }
        
        // 考试是否包含导入学校
        $exam_where = " WHERE  \"exam_id\"='{$examID}'";
        $exam_school = Nojoin::_getexam_schoolALL($exam_where);
        $exam_school_id = array();
        foreach ($exam_school as $v){
            $exam_school_id[] = $v['school_id'];
        }
        if (!in_array($schoolID, $exam_school_id)) {
            Z::ajaxReturn(206, '该考试项目不包含此学校');
        }
        
        // 保存excel
        $uniqueName = ZFileUpload::getUniqueID();  #得到唯一名称
        $tmpExcel = $_FILES['file']['tmp_name'];
        $pickFilePath = ZPScoreImport::getExcelSavePath(ZPScoreImport::UPLOAD_STUDENT).'/'.$uniqueName.'.pick';
        //echo $tmpExcel;exit;
        // 判断excel是否为空
        $excelImport = new ZPScoreImport($tmpExcel, 1);
        $excelInfo = $excelImport->pickExcel($tmpExcel, $pickFilePath);
        $ExcelRowCount = $excelInfo['rowNum'];
        if( $ExcelRowCount < 2 ){
            $this->ajaxReturn(209,"excel数据为空");
        }
        
        // ajax 返回上传结果
        $salt = ZPScoreImport::salt($uniqueName.$examID.$schoolID."1"."0".$ExcelRowCount);
        $this->ajaxReturn(1,"文件上传成功",array(
            'f'     =>  base64_encode($uniqueName),
            'eid'   =>  $examID,
            'sid'   =>  $schoolID,
            'bt'    =>  1,
            'he'    =>  0,
            'salt'  =>  $salt,
            'ct'    =>  $ExcelRowCount
        ));
        
        
    }
    public function ActionVerifyExcel(){
        // request 参数
        $uniqueFileName = urldecode(base64_decode($this->request->getParam('f','')));
        $examID = $this->request->getParam('eid','');
        $schoolID = $this->request->getParam('sid','');
        $batch = intval($this->request->getParam('bt',"0"));
        $hasError = $this->request->getParam('he',"0");
        $reqSalt = $this->request->getParam('salt','');
        $rcount   = $this->request->getParam('ct',0);
        $salt = ZPScoreImport::salt($uniqueFileName.$examID.$schoolID.$batch.$hasError.$rcount);
        
        // 非正常请求
        if(empty($uniqueFileName) || empty($examID) || empty($schoolID) || empty($reqSalt) || $batch<1)
            $this->ajaxReturn(201,'校验失败');
        if($reqSalt !== $salt)
            $this->ajaxReturn(202,'校验失败');
        $pickFilePath = trim(ZPScoreImport::getExcelSavePath(ZPScoreImport::UPLOAD_STUDENT),"\\/").DIRECTORY_SEPARATOR.$uniqueFileName.".pick";
        if(!file_exists($pickFilePath)){
            $this->ajaxReturn(203,'校验失败');
        }
        
        //得到学校信息
        $where = ' WHERE "school_id"= '.$schoolID;
        $school_info = Nojoin::_getschoolAll($where); 
        // 读取excel
        $excelImport = new ZPScoreImport($pickFilePath, 1);
        $pdata = $excelImport->fetchPickBatch($batch, $pickFilePath, ZPScoreImport::BATCHNUM);
        $Sheet = $pdata['data'];
        $rowCount = count($Sheet);
        $sheetTitle = $pdata['title'];
        $exam_reportrule = Nojoin::_getreportruleALL();
        $exm_student_array = array();
        $exm_student_array['exam_id'] = $examID;
        $exm_student_array['city_code'] = $exam_reportrule[0]['code'];
        $exm_student_array['city_name'] = $exam_reportrule[0]['name'];
        $exm_student_array['school_id'] = $school_info[0]['school_id'];
        $exm_student_array['school_code'] = $school_info[0]['school_code'];
        $exm_student_array['school_name'] = $school_info[0]['school_name'];
        $exm_student_array['socre'] = 0;
        $exm_student_array['statis'] = 'F';
        $exm_student_array['addtime'] = time();
        $importruledetail = Array(
        '准考号' => 'exam_code',
        '班级' => 'class_name',
        '科别简称' => 'disciplin_name',
        '姓名' => 'student_name',
        '性别' => 'student_sex',
        //'中考成绩' => 'socre',
        '统计' => 'default_statis',
        '学校性质' => 'nature',
        '学校星级' => 'interstellar',
        '学籍号' => 'roll',
        '备注' => 'ramark',
        );
        
        if(array_search('姓名', $sheetTitle)===false){
            $this->ajaxReturn(224,'姓名列为必填列');
        }
        // 批处理sql
        $batch_sql = '';
        $batch_error_sql = '';
        //$studentDPIndex = array_search('科别简称',$sheetTitle);
        
        // 数据库和缓存中考生号
        $dbExamCodes = array();     # 判断数据库中是否存在考生号码
        $batchExamCodes = array();  # 批数据中所有的考生号
        $cacheExamCodes = ZPScoreImport::fetchUniqueCache($uniqueFileName);
        $cacheExamCodes = $cacheExamCodes?$cacheExamCodes:array();
        $examCodeIndex = array_search('准考号', $sheetTitle);   #考号对应的excel列下标
        if($examCodeIndex !== false){
            foreach($Sheet AS $v){
                $sheetExamCode = isset($v[$examCodeIndex])?trim($v[$examCodeIndex]):null;
                if($sheetExamCode){
                    $batchExamCodes[$sheetExamCode] = $sheetExamCode;
                }
            }
        }
        if($batchExamCodes){
            $batchExamCodes = implode("','", $batchExamCodes);
            $dbCodeSql = "SELECT \"exam_code\" FROM  \"{{student}}\" 
                            WHERE \"exam_code\" IN ('{$batchExamCodes}') 
                            AND \"exam_id\"='{$examID}' 
                            AND \"school_id\"='{$schoolID}'";
            $studentRow = Yii::app()->db->createCommand($dbCodeSql)->queryAll();
            if($studentRow)
                foreach($studentRow AS $studentRv){
                    $dbExamCodes[$studentRv['exam_code']] = 1;
                }
            unset($studentRow,$dbCodeSql,$batchExamCodes);
        }
        
        // 数据库中可用可用科别
        $dpSql = 'SELECT "disciplin_nick","disciplin_code","disciplin_type"  FROM "{{disciplin}}" WHERE "is_del"=0';
        $dbDp = array();
        $dbDpRow = Yii::app()->db->createCommand($dpSql)->queryAll();
        if($dbDpRow){
            foreach($dbDpRow AS $dpRv){
                $dbDp[$dpRv['disciplin_nick']] = $dpRv;
            }
        }
        
        // 处理excel中的批数据
        foreach ($Sheet as $k => $v) {
            $errorRow = ZPScoreImport::BATCHNUM * ($batch -1) + 2;
            // 单元格对应数据库字段
            $sheetary = array_combine($sheetTitle, $v);
            foreach ($sheetary as $s => $y) {
                if (isset($importruledetail[$s])) {
                    $exm_student_array[$importruledetail[$s]] = trim($y);
                }
            }
            // 学生姓名不能为空
            $exm_student_array['student_name'] = isset($exm_student_array['student_name'])? preg_replace('/[\s| ]+/', '', $exm_student_array['student_name']):"";
            if (!$exm_student_array['student_name']){
                $batch_error_sql .= 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $errorRow . ',\'姓名不能为空\',1,' . $examID . ');
                    ';
                continue;
            }
            
            // 考生号重复判断
            $exm_student_array['exam_code'] = isset($exm_student_array['exam_code'])?trim($exm_student_array['exam_code']):'';
            //var_dump(isset($cacheExamCodes[$exm_student_array['exam_code']]));echo $exm_student_array['exam_code'];
            if(isset($dbExamCodes[$exm_student_array['exam_code']]) || isset($cacheExamCodes[$exm_student_array['exam_code']])){
                $batch_error_sql .= ' INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $k . ',\'此' . $exm_student_array['exam_code'] . '考号已经存在\',1,' . $examID . '); 
                                    ';
                continue;
            }
            if($exm_student_array['exam_code']){
                $cacheExamCodes[$exm_student_array['exam_code']] = 1;
            }
            
            
            //判定分数是否是数字                            
            /*if(isset($exm_student_array['socre']) && !empty($exm_student_array['socre'])){
                if(!is_numeric($exm_student_array['socre'])){
                    $batch_error_sql .= 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $errorRow . ',\'中考成绩格式错误\',1,' . $examID . ');
                    ';
                    continue;
                }
            }*/
            
            // 性别
            if (isset($exm_student_array['student_sex'])) {
                if ($exm_student_array['student_sex'] == '男')
                $exm_student_array['student_sex'] = 1;
                if ($exm_student_array['student_sex'] == '女')
                $exm_student_array['student_sex'] = 2;
            }else{
                $exm_student_array['student_sex'] = 0;
            }
            
            // 科别判断
            $exm_student_array['disciplin_name'] = isset($exm_student_array['disciplin_name'])?trim($exm_student_array['disciplin_name']):'';
            if ($exm_student_array['disciplin_name']){
                if(isset($dbDp[$exm_student_array['disciplin_name']])) {
                    $exm_student_array['disciplin_code'] = $dbDp[$exm_student_array['disciplin_name']]['disciplin_code'];
                    $exm_student_array['disciplin_type'] = $dbDp[$exm_student_array['disciplin_name']]['disciplin_type'];
                }else{
                    $batch_error_sql .= 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $errorRow . ',\'此科别'.$exm_student_array['disciplin_name'].'没有科别信息\',1,' . $examID . ');
					';
                    continue;
                }
            }

            if ($exm_student_array) {
                $sqlkey = array_keys($exm_student_array);
                $sqlkey = '"'.implode('","', $sqlkey).'"';
                $sqlvalue = array_values($exm_student_array);
                $sqlvalue = "'" . implode("','", $sqlvalue) . "'";
                $sql = 'INSERT INTO "{{student}}" (' . $sqlkey . ') VALUES (' . $sqlvalue . ');
                        ';
                $batch_sql .= $sql;
            }
        }
        ZPScoreImport::saveUniqueCache($cacheExamCodes, $uniqueFileName);//var_dump($cacheExamCodes);exit;
		
		
        if ($batch_error_sql) {
            //将本次项目导入之前错误日志清空
            if($batch == 1){
                $batch_error_sql = "DELETE FROM \"{{import_error}}\"  WHERE \"type\"=1 AND \"exam_id\"= '{$examID}';
                                    {$batch_error_sql}";
            }
            $hasError = 1;
            ZPScoreImport::clearBatchSqlAll($uniqueFileName);
            $batch_error_sql = "DECLARE
                               BEGIN
                               {$batch_error_sql}
                               END;"; 
            Yii::app()->db->createCommand($batch_error_sql)->execute();
        } else {
            if ($batch_sql) {
                $batch_sql = " --<$rowCount>
                               DECLARE
                               BEGIN
                               {$batch_sql}
                               END;";
                ZPScoreImport::saveBatchSql($batch, $uniqueFileName, $batch_sql);
            }
        }
        $readStatus = $pdata['readEnd'];
        // ajax 返回验证结果
        if($readStatus == 1){
            $batch = 1;
        }else{
            $batch ++;
        }
        $salt = ZPScoreImport::salt($uniqueFileName.$examID.$schoolID.$batch.$hasError.$rowCount);
        $this->ajaxReturn($readStatus,"文件上传成功",array(
            'f'     =>  base64_encode($uniqueFileName),
            'eid'   =>  $examID,
            'sid'   =>  $schoolID,
            'bt'    =>  $batch,
            'he'    =>  $hasError,
            'salt'  =>  $salt,
            'ct'    =>  $rowCount
        ));
    }
    public function ActionSaveexcel(){
        // request 参数
        $uniqueFileName = urldecode(base64_decode($this->request->getParam('f','')));
        $examID = $this->request->getParam('eid','');
        $schoolID = $this->request->getParam('sid','');
        $batch = $this->request->getParam('bt',0);
        $hasError = $this->request->getParam('he',0);
        $reqSalt = $this->request->getParam('salt','');
        $rcount   = $this->request->getParam('ct',0);
        $salt = ZPScoreImport::salt($uniqueFileName.$examID.$schoolID.$batch.$hasError.$rcount);
        if(empty($uniqueFileName) || empty($uniqueFileName) || empty($examID) || empty($schoolID) || empty($reqSalt) || $batch<1)
            $this->ajaxReturn(201,'校验失败');
        if($reqSalt !== $salt)
            $this->ajaxReturn(202,'校验失败');
        
        
        $count = 0;
        $content = ZPScoreImport::fetchBatchSql($batch, $uniqueFileName);
        if($content){
            $begin  = strpos($content,'<')+1;
            $end  = strpos($content,'>');
            $count = substr($content, $begin, $end-$begin);
            Yii::app()->db->createCommand($content)->query();
            //@unlink($sqlFile);
            // ajax 返回验证结果
            $batch ++;
            $salt = ZPScoreImport::salt($uniqueFileName.$examID.$schoolID.$batch.$hasError.$count);
            $this->ajaxReturn(2,"文件上传成功",array(
                'f'     =>  base64_encode($uniqueFileName),
                'eid'   =>  $examID,
                'sid'   =>  $schoolID,
                'bt'    =>  $batch,
                'he'    =>  $hasError,
                'salt'  =>  $salt,
                'ct'    =>  $count,
            ));
        }
        $this->ajaxReturn(1);
    }
    private function ajaxReturn($code,$msg='',$ext=''){
        $res = array('code'=>$code,'msg'=>$msg, 'ext'=>$ext);
        echo  json_encode($res);exit;
    }
    //上传文件
	/*public function actionImport(){
		if(!empty($_POST['submit'])){
			$data = $this->request->getParam('info');
			if (empty($data['exam_id']) || empty($_FILES['file']['name']) || empty($data['school_id'])) {
				$this->redirect('/info/default/index/error/1');exit;
			} else {
				//得到学生信息
				$userinfo = $this->cLoginUser;
				if (!empty($userinfo)) {
					if ($userinfo['cuser']['role_id'] != 1) {//超级管理员可以导入任何学校
						$userid = $userinfo['cuser']['id'];
						$studentinfo = Import::_getstudentinfo($userid);
						if (empty($studentinfo)){
							$this->redirect('/info/default/index/error/8');  exit;
						}
						//判断当前用户是否有导入所选学校的权限
						$school_ids = $studentinfo['school_id'];
						$school_id = $data['school_id'];
						if (!strpos($school_ids, $school_id)) {
							$this->redirect('/info/default/index/error/2');exit;
						}
					}
				}
				//得到项目信息
				$examwhere = ' AND "exam_id"='.$data['exam_id'];
				$exam = ZTask::_getExamAll($examwhere);
				$exam_where = ' WHERE "exam_id"='.$data['exam_id'];
				$exam_school = Nojoin::_getexam_schoolALL($exam_where);
				$exam_school_id = array();
				foreach ($exam_school as $k=>$v){
					$exam_school_id[] = $v['school_id'];
				}
				if (!in_array($data['school_id'], $exam_school_id)) {
					$this->redirect('/info/default/index/error/3');exit;
				}
				//得到学校信息
				$where = ' WHERE "school_id"= ' . $data['school_id'];
				$school_info = Nojoin::_getschoolAll($where);
				//得到城市代码
				$exam_reportrule = Nojoin::_getreportruleALL();
				$conn = Yii::app()->db;
				if (isset($_FILES['file'])) {
					$file_name_list = ZFileUpload::getUniqueID();  //得到唯一名称
					$file_name = $_FILES['file']['name'];
					$extend = pathinfo($file_name);
					$extend = strtolower($extend["extension"]);
					$file_name_list .= '.' . $extend;    //得到文件后缀
					$upload_file_name = UPLOAD_PATH . '/info/' . $file_name_list;
					$file_type = move_uploaded_file($_FILES['file']['tmp_name'], $upload_file_name);
					if ($file_type == 1) {
                        if(!ZPScoreImport::isSupportExcelVersion($upload_file_name)){
                            $this->redirect('/info/default/index/error/6');exit;
                        }
						$excelImport = new ZPScoreImport($upload_file_name, 1);
                        $pdata = $excelImport->fetchAll();
						$Sheet = $pdata['data'];
                        $sheetTitle = $pdata['title'];
                        //var_dump($sheetTitle);exit;
						$exm_student_array = array();
						$exm_student_array['exam_id'] = $data['exam_id'];
						$exm_student_array['city_code'] = $exam_reportrule[0]['code'];
						$exm_student_array['city_name'] = $exam_reportrule[0]['name'];
						$exm_student_array['school_id'] = $school_info[0]['school_id'];
						$exm_student_array['school_code'] = $school_info[0]['school_code'];
						$exm_student_array['school_name'] = $school_info[0]['school_name'];
                        $exm_student_array['default_statis'] = 'T';
						$exm_student_array['addtime'] = time();
						$importruledetail = Array(
						'准考号' => 'exam_code',
						'班级' => 'class_name',
						'科别简称' => 'disciplin_name',
						'姓名' => 'student_name',
						'性别' => 'student_sex',
						'中考成绩' => 'socre',
						'统计' => 'default_statis',
						'学校性质' => 'nature',
						'学校星级' => 'interstellar',
						'学籍号' => 'roll',
						'备注' => 'ramark'
						);
						$student_sql = array();
						$student_error_sql = array();
						$excelcount = $pdata['rowNum'];
						if ($excelcount<2){
							$this->redirect('/info/default/index/error/7');exit;
						}
                        
						foreach ($Sheet as $k => $v) {
                            $sheetary = array_combine($sheetTitle, $v);
                            foreach ($sheetary as $s => $y) {
                                if (isset($importruledetail[$s])) {
                                    $exm_student_array[$importruledetail[$s]] = trim($y);
                                }
                            }
                            if (isset($exm_student_array['exam_code'])){
                                $exm_student_array['exam_code'] = preg_replace('/[\s| ]+/', '', $exm_student_array['exam_code']);
                            }
                            if (isset($exm_student_array['student_name'])){
                                $exm_student_array['student_name'] = preg_replace('/[\s| ]+/', '', $exm_student_array['student_name']);
                            }
                            //if (!isset($exm_student_array['exam_code']) || !isset($exm_student_array['student_name'])){
                            //	$errorsql = 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $k . ',\'考号和姓名不能为空\',1,' . $data['exam_id'] . ')';
                            if (!isset($exm_student_array['student_name'])){
                                $errorsql = 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $k . ',\'姓名不能为空\',1,' . $data['exam_id'] . ')';
                                $student_error_sql[] = $errorsql;
                                continue;
                            }
                            //判定分数是否是数字                            
                            if(isset($exm_student_array['socre']) && !empty($exm_student_array['socre'])){
                                if(!is_numeric($exm_student_array['socre'])){
                                    $errorsql = 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $k . ',\'中考成绩格式错误\',1,' . $data['exam_id'] . ')';
                                    $student_error_sql[] = $errorsql;
                                    continue;
                                }
                            }

                            //判断考号是否符合
                            if (isset($exm_student_array['exam_code']) && !empty($exm_student_array['exam_code'])) {
                                if (!empty($exam[0]['exam_num']) && strlen($exm_student_array['exam_code']) != $exam[0]['exam_num']) {
                                    $errorsql = 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $k . ',\'考号不是' . $exam[0]['exam_num'] . '位数\',1,' . $data['exam_id'] . ')';
                                    $student_error_sql[] = $errorsql;
                                    continue;
                                }
                            }
                            //判断考号是否存在
                            if (!empty($exm_student_array['exam_code'])) {
                                $where = ' WHERE "exam_id"=' . $data['exam_id'] . ' AND "exam_code"=' . $exm_student_array['exam_code'];
                                $checkstudentinfo = Import::_checkstudentinfo($where);
                                if (!empty($checkstudentinfo)) {
                                    $errorsql = 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $k . ',\'此' . $exm_student_array['exam_code'] . '考号已经存在\',1,' . $data['exam_id'] . ')';
                                    $student_error_sql[] = $errorsql;
                                    continue;
                                }
                            }
                            if (isset($exm_student_array['student_sex'])) {
                                if ($exm_student_array['student_sex'] == '男')
                                $exm_student_array['student_sex'] = 1;
                                if ($exm_student_array['student_sex'] == '女')
                                $exm_student_array['student_sex'] = 2;
                            }
                            if (isset($exm_student_array['disciplin_name'])) {
                                $where = ' WHERE "disciplin_nick" like \'%' . $exm_student_array['disciplin_name'] . '%\'';
                                $disciplininfo = Import::_getdisciplininfo($where);
                                if (!empty($disciplininfo)) {
                                    $exm_student_array['disciplin_code'] = $disciplininfo['disciplin_code'];
                                    $exm_student_array['disciplin_type'] = $disciplininfo['disciplin_type'];
                                }else{
                                    $errorsql = 'INSERT INTO "{{import_error}}" ("excel_row","info","type","exam_id") VALUES (' . $k . ',\'此科别'.$exm_student_array['disciplin_name'].'没有科别信息\',1,' . $data['exam_id'] . ')';
                                    $student_error_sql[] = $errorsql;
                                    continue;
                                }
                            }

                            if ($exm_student_array) {
                                $sqlkey = array_keys($exm_student_array);
                                $sqlkey = '"'.implode('","', $sqlkey).'"';
                                $sqlvalue = array_values($exm_student_array);
                                $sqlvalue = "'" . implode("','", $sqlvalue) . "'";
                                $sql = 'INSERT INTO "{{student}}" (' . $sqlkey . ') VALUES (' . $sqlvalue . ')';
                                $student_sql[] = $sql;
                            }
						}
						if ($student_error_sql) {
							//将本次项目导入之前错误日志清空
							//$error_where = ' WHERE "type"=1 AND "exam_id"=' . $data['exam_id'];
							//Import::_delimporterror($error_where);
                            $errorSql = "DELETE FROM \"{{import_error}}\"  WHERE \"type\"=1 AND \"exam_id\"= '{$data['exam_id']}' ; ";
                            $errorSql .= implode(" ; ", $student_error_sql);
							//foreach ($student_error_sql as $sql) {
                            $conn->createCommand($sql)->execute();
							//}
							$this->redirect('/info/default/index/error/4/exam_id/' . $data['exam_id']);exit;
						} else {
							if ($student_sql) {
                                $studentSql = "DECLARE
                                                BEGIN
                                               ";
                                $studentSql .= implode(" ; ", $student_sql);
                                $studentSql .= ";
                                                END;";
								//foreach ($student_sql as $sql) {
								@$conn->createCommand($studentSql)->execute();
								//}
							}
						}
						$this->redirect('/info/default/index/error/5');exit;
					}
				}
			}
		}
		$this->redirect('/info/default/index');
	}*/
}
